package jd;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;

public class LoginAction implements Action {
    @Override
    public void execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //  从request中取值，判断账号密码是否正确，根据结果导航
        String account = request.getParameter("account");
        String password = request.getParameter("password");

        //  得到DOM解析器的工厂实例
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        try {
            //  从DOM工厂获得DOM解析器
            DocumentBuilder db = dbf.newDocumentBuilder();
            //  解析XML文档，得到一个Document对象，即DOM树
            Document doc = db.parse("Java开发之框架基础技术/ch03/hard/src/com/bdqn/xml/User.xml");
            //  得到所有Info节点列表信息
            NodeList infoList = doc.getElementsByTagName("Info");
            //  循环Info信息
            for (int i = 0; i <infoList.getLength() ; i++) {
                //  获取第i个Info元素信息
                Node info = infoList.item(i);
                //  获取第i个Info元素的所有子元素的id属性值
                NodeList types = info.getChildNodes();
                for (int j = 0; j <types.getLength() ; j++) {
                    if(types.item(j).getNodeType() == Node.ELEMENT_NODE){
                        Element typeElement = ((Element) types.item(j));  //  Type节点
                        String act = typeElement.getFirstChild().getTextContent();
                        String pwd = typeElement.getLastChild().getTextContent();
                        if (act.equals(account) && pwd.equals(password)) {
                            request.getRequestDispatcher(request.getContextPath() + "home.jsp").forward(request, response);
                            return;
                        } else {
                            request.getRequestDispatcher(request.getContextPath() + "index.jsp").forward(request, response);
                        }
                    }
                }
            }
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
